<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page language="java" import="com.uft.model.entity.*,java.util.List"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ page isELIgnored="false"%>
<script>
$(function () {
	var plotData =[];
	var autoRefreshIntervalId =0;
	var chartInterval=6000;
	$( "#DPleftNavAccord" ).accordion({ header: "h3", heightStyle: "fill" });
	$( "#DPMainAccord" ).accordion({ header: "h3", heightStyle: "fill" });
	$( "#interval" ).selectBoxIt(
	  {
		  theme: "jqueryui" 
	  }).on("change", function() {
		  drawChart();
	  });
	
	  $( "#dpProfiles" ).selectBoxIt(
	  {
		    // Uses the jQueryUI theme for the drop down
		    theme: "jqueryui",
	    	populate: function() {
	            var deferred = $.Deferred(),
	                arr = [],
	                x = -1;
	            $.ajax({
	            	type: "POST",
	                url: 'getDPProfileList.htm',
	                dataType: 'json',
	                beforeSend: function(){
	                	
	                },
	                complete: function () {
	                	
	                }
	            
	            }).done(function(data) {
	                while(++x < data.Records.length) {
	                    arr.push(data.Records[x].dpName);
	                }
	                deferred.resolve(arr);
	            });
	            return deferred;
	        }
	  }).on("change", function() {
		  updateChartData();
		  drawChart();
	   });
	  var timeSlice= $( "#timeSlice" ).selectBoxIt(
		  {
			    // Uses the jQueryUI theme for the drop down
			    theme: "jqueryui"
		   }).on("change", function() {
			   $('#from').val("");
			   $('#to').val("");
			   updateChartData();
			   drawChart();
		   });
	  var data = [
	            {
	            	label: "Memory",
	            	id: 'memory',
	            	type: 'root',
	            	children: [
	            	           { label: "totalMemory", id: "totalMemory", type:"MB" },
	            	           { label: "holdMemory", id: "holdMemory",type:"MB" },
	            	           { label: "freeMemory", id: "freeMemory",type:"MB" },
	            	           { label: "usedMemory", id: "usedMemory",type:"MB" },
	            	           { label: "memoryUsage", id: "memoryUsage",type:"%" },
	            			  ]
	            },
	            {
	            	label: "CPU",
	            	id: 'cpuType',
	            	type: 'root',
	            	children: [
	            	           { label: "cpuUsageLastTenMin", id: "cpuUsageLastTenMin", type:"%" }
	            	           
	            			  ]
	            }
	            
	            ]
	$('#DPleftNav').tree({
		data: data,
		
		autoOpen: true,
		onCreateLi: function(node, $li) {
	        // Add 'icon' span before title
			var level = node.getLevel();
			var icon;
			 if (level == 1) {
				 icon = 'fa fa-folder-open-o';
			 }else if (node.children.length != 0) {
				 icon = 'fa fa-folder-open-o';
			 }else {
				 icon = 'fa fa-bar-chart-o';
			 }
			 var $title = $li.find('.jqtree-title');
			 $title.prepend(
	            $('<i class="' + icon + '"></span>')
	         );
   
	    }
	})
	$('#DPleftNav').bind('tree.select',function(event){
		
		if (event.node) {
			var node = event.node;
			var name=node.name;
			var type =node.type;
			if(type != "root"){
				drawChart();	
			}
		}
		
	})
	
	$("#dpProfileDialog").dialog({
		autoOpen: false,
		resizable: false,
		width: "auto"
  	});
	$( "#profiles" ).button().click(function( event ) {
		  if ($("#dpProfileDialog").dialog("isOpen") == false) {
				$("#dpProfileDialog").dialog("open");
				 $('#dpProfileTable').jtable('load');
			}
	});
	$('#dpProfileTable').jtable({
		  title: 'Datapower Profiles',
		  selecting: true,
      selectingCheckboxes: true,
      multiselect: false,
      actions: {
          listAction: 'getDPProfileList.htm',
          createAction: 'addDPProfile.htm',
          updateAction: 'updateDPProfile.htm',
          deleteAction: 'deleteDPProfile.htm'
      },
      fields: {
    	  id: { key: true,list: false },
    	  dpRegion: { title: 'Region'},
    	  dpName: { title: 'Name'},
    	  dpHostname: { title: 'Hostname'},
    	  dpPort: { title: 'Port'},
    	  dpUsername: { title: 'Username'},  
    	  dpPassword: {
              title: 'Password',
              type: 'password',
              list: false
          },
    	  enableStats: { title: 'Enable Stats',
              type: 'checkbox',
              values: { 'false': 'false', 'true': 'true' },
              defaultValue: 'false' }
      }
	  });
	 var startDateTextBox = $('#from');
	 var endDateTextBox = $('#to');
	 startDateTextBox.datetimepicker({ 
		  	timeFormat: "HH:mm",
		  	onClose: function(dateText, inst) {
		  		if (endDateTextBox.val() != '') {
		  			var testStartDate = startDateTextBox.datetimepicker('getDate');
		  			
		  			var testEndDate = endDateTextBox.datetimepicker('getDate');
		  			if (testStartDate > testEndDate)
		  				endDateTextBox.datetimepicker('setDate', testStartDate);
		  		}
		  		else {
		  			endDateTextBox.val(dateText);
		  		}
		  	},
		  	onSelect: function (selectedDateTime){
		  		
		  		endDateTextBox.datetimepicker('option', 'minDate', startDateTextBox.datetimepicker('getDate') );
		  	},
		  	addSliderAccess: true,
			sliderAccessArgs: { touchonly: false }
		  });
		 endDateTextBox.datetimepicker({ 
		  	timeFormat: "HH:mm",
		  	onClose: function(dateText, inst) {
		  		if (startDateTextBox.val() != '') {
		  			var testStartDate = startDateTextBox.datetimepicker('getDate');
		  			var testEndDate = endDateTextBox.datetimepicker('getDate');
		  			if (testStartDate > testEndDate)
		  				startDateTextBox.datetimepicker('setDate', testEndDate);
		  		}
		  		else {
		  			startDateTextBox.val(dateText);
		  		}
		  	},
		  	onSelect: function (selectedDateTime){
		  		startDateTextBox.datetimepicker('option', 'maxDate', endDateTextBox.datetimepicker('getDate') );
		  	},
		  	 addSliderAccess: true,
			  sliderAccessArgs: { touchonly: false }
		});
	  $( "#refresh" ).button().click(function( event ) {
		  $( "#interval" ).selectBoxIt().val("1 day");
		  updateChartData();
		  drawChart();
		  
	  });
	  function updateChartData(){
		 var getFromDate=startDateTextBox.datetimepicker('getDate');
		 var toFromDate=endDateTextBox.datetimepicker('getDate');
		// console.log("getFromDate: "+getFromDate.getMonth())
		// console.log("toFromDate: "+toFromDate)
		 var timeSliceValue= timeSlice.val();
		 var fromDate;
		 var toDate;
		 if(getFromDate != null && toFromDate != null){
			 fromDate=eval(getFromDate.getMonth()+1)+"/"+getFromDate.getDate()+"/"+getFromDate.getFullYear()+
	 			" "+getFromDate.getHours()+":"+getFromDate.getMinutes();
	 		 toDate=eval(toFromDate.getMonth()+1)+"/"+toFromDate.getDate()+"/"+toFromDate.getFullYear()+
				" "+toFromDate.getHours()+":"+toFromDate.getMinutes();
		 }else{
			 var toDateObj=new Date();
			 var fromDateObj=new Date();
			 if(timeSliceValue == "10m"){
				 fromDateObj.setMinutes(toDateObj.getMinutes()-10);
			 }else if(timeSliceValue == "1h"){
				 fromDateObj.setHours(toDateObj.getHours()-1);
			 }else if(timeSliceValue == "4h"){
				 fromDateObj.setHours(toDateObj.getHours()-4);
			 }else if(timeSliceValue == "8h"){
				 fromDateObj.setHours(toDateObj.getHours()-8);
			 }else if(timeSliceValue == "1d"){
				 fromDateObj.setHours(toDateObj.getHours()-24);
			 }else{
				 fromDateObj.setMinutes(toDateObj.getMinutes()-5);
			 }
			 fromDate=eval(fromDateObj.getMonth()+1)+"/"+fromDateObj.getDate()+"/"+fromDateObj.getFullYear()+
			 			" "+fromDateObj.getHours()+":"+fromDateObj.getMinutes();
			 toDate=eval(toDateObj.getMonth()+1)+"/"+toDateObj.getDate()+"/"+toDateObj.getFullYear()+
	 			" "+toDateObj.getHours()+":"+toDateObj.getMinutes();
		 }
		 var dpName= $( "#dpProfiles" ).selectBoxIt().val();
		
		 $.ajaxq("plot",{
		    	async: false,
				type: "POST",
				url: "getDpRunTimeDataByStartEnd.htm",
			    dataType: 'json',
			    data: {
			    	dpName: dpName,
			    	startTime: fromDate,
			    	endTime: toDate
			    	
			    },
			    success: function( data ) {
			    	plotData= data.Records;
			    },
			    
			  });  	
		 }
	  function drawChart() {
			 
	//	if(plotData.length == 0){
		//		updateChartData();
	//	}
		var nodes = $('#DPleftNav').tree('getSelectedNodes');
		if(nodes.length <= 0){
			return 
		}
	   var child = nodes[0];
	   var name=child.name;
	   var id =child.id;
	   var type=child.type;
	  if(typeof id != 'undefined'){			
			var title=name;
			//var type=$('#leftNav').jstree('get_selected').parents("li").attr("id");
			$('#DPMainAccord div h3').text(title)
			
			$.jqplot('mainChart',id,{
			    title: title+"("+$( "#dpProfiles" ).selectBoxIt().val()+")",
			    dataRenderer: function(id){
			    		var data = [[]];
			    		if(plotData.length > 0){
			    			$("#dataStatus").html("<font color='green'>Data Available!</font>");
			    			for (var i = 0; i < plotData.length; i++ ) {
								 var obj=plotData[i]; 
								 if(id in obj){
									 var idValue=obj[id];
									 var date = new Date(obj.genTimeStamp);
									 if(type == "MB"){	 
										idValue=eval(idValue/1024);
										//console.log(idValue);
									 }
									 
									 data[0].push([date, idValue]);
								 }
								 
							 }
			    		}else{
			    			//data = [[null]];
			    			var date = new Date();
			    			data[0].push([date, ""]);
			    			$("#dataStatus").html("<font color='red'>Data UnAvailable!</font>");
			    			
			    			
			    		}
						 
					 return data;
			    },
			    series:[{color:'#5FAB78'}],
			    axes:{
			    	xaxis:{
			    		renderer:$.jqplot.DateAxisRenderer,
			    		tickOptions:{
	                        formatString:'%m/%d/%y %H:%M'
	                    },
			   			tickInterval:$( "#interval" ).selectBoxIt().val(),
			   			label:'Date'
			    	},
			    	yaxis:{
			            label:function(){
			            	if(type == "MB"){
			            		return "Memory(MB)";
			            	}
			            	if(type == "%"){
			            		return "Percentage(%)";
			            	}
			            	return "";
			            }
			          }
			    },
			    highlighter: {
		      	  show: true,
		      	  sizeAdjust: 7.5
		     	 },
			    cursor:{ 
			        show: true,
			        zoom:true, 
			        showTooltip:false
			      } 
			  }).redraw(true);
		}
		 
	 }
});
</script>

<div id="toolbar" class="filtering">	
	<select  id="dpProfiles" name="Profiles">
			
	</select>
	<select style="color: #2191c0;" id="timeSlice" name="timeSlice">
			<option value="5m" selected="selected">5 Min</option>
			<option value="10m">10 Min</option>
			<option value="1h">1 Hour</option>
			<option value="4h">4 Hour</option>
			<option value="8h">8 Hour</option>
			<option value="1d">1 day</option>
	</select>
	<div style="float:right">
		
		<button id="profiles">DP Profiles</button>
	</div>				
</div>
<div id="toolbar" class="filtering">
	<table >
			<tr>
			<td><label for="from">From</label></td>
			<td><input type="text" id="from" name="from"></td>
			<td><label for="to">to</label></td>
			<td><input type="text" id="to" name="to"></td>
			<td><button id="refresh">Refresh</button></td>
			</tr>
	</table>	
	<div style="float:right">
		<span>Interval</span>
		<select  id="interval" name="interval">
				<option value="10 minute" >10 Min</option>
				<option value="15 minute" >15 Min</option>
				<option value="30 minute" selected="true">30 Min</option>
				<option value="1 hour" >1 hour</option>
				<option value="4 hour" >4 hour</option>
				<option value="6 hour" >6 hour</option>
				<option value="1 day">1 Day</option>
				<option value="1 month">1 Month</option>
				<option value="1 year">1 Year</option>
		</select>	
		<span id="dataStatus"></span>						
	</div>
</div>
<table style="width:100%; height:90%">
<tr>
	<td width="20%" valign="top">
		<div id="DPleftNavAccord">	
				<div class="acc-content">
					<h3>Info</h3>
		        	<div><div id="DPleftNav" class="leftNav"></div></div>
				</div>
		</div>
	</td>
	<td valign="top" >
		
		<div id="DPMainAccord">	
				
				<div class="acc-content">
					<h3><a href="#">Detail</a></h3>
		        	<div><div id="mainChart" class="leftNav"></div></div>
				</div>
		</div>
	</td>
</tr>
</table>
<div id="dpProfileDialog" title="Datapower Profiles">
 <div id="dpProfileTable">
 </div>	
</div>